import React, {Component} from 'react'
import {Button, Jumbotron} from "react-bootstrap";
import QrReader from "react-camera-qr";
import {getProfile, giveBack, rent} from "./utils";

class Main extends Component {
    state = {
        scanning: false,
        mode: 'rent',
        result: ''
    }

    async onScan(data) {
        if(!data) return
        if(this.state.mode === 'rent') {
            await this.onRent(data)
        } else {
            await this.onGiveBack(data)
        }
    }

    async onRent(seat_id) {
        let code = await rent(seat_id, this.props.state.token)
        alert(code)
        if(code?.length === 6) {
            await this.setState({scanning: false})
            let user = await getProfile(this.props.state.token)
            await this.props.setState({user: user})
        }
    }

    async onGiveBack(data) {
        let [machine_id, totp] = data.split('#')
        machine_id = Number(machine_id)
        console.log(machine_id, totp)
        let res = await giveBack(machine_id, this.props.state.token, totp)
        if(res.ok) {
            await this.setState({scanning: false})
            let user = await getProfile(this.props.state.token)
            await this.props.setState({user: user})
            alert('还凳成功！')
        } else {
            alert(await res.text())
        }
    }

    getPage() {
        if (!this.props.state.user?.seatId && !this.state.scanning) {
            return (
                <Jumbotron>
                    <Button variant="primary" size="lg" onClick={() => {
                        this.setState({scanning: true, mode: 'rent'})
                    }}>扫码用凳</Button>
                </Jumbotron>
            )
        } else if (this.props.state.user?.seatId && !this.state.scanning) {
            return (
                <Jumbotron>
                    <Button variant="primary" size="lg" onClick={() => {
                        this.setState({scanning: true, mode: 'give_back'})
                    }}>还凳</Button>
                </Jumbotron>
            )
        } else {
            return (
                <div>
                    <QrReader
                        delay={300}
                        onError={console.error}
                        onScan={this.onScan.bind(this)}
                        style={{width: '100%', height: '100%'}}
                    />
                </div>
            )
        }
    }

    render() {
        return this.getPage()
    }
}

export {Main}